/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.business.rest;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.business.domain.Order;
import me.zhengjie.business.domain.sup.Gsgl;
import me.zhengjie.business.service.GsglService;
import me.zhengjie.business.service.OrderService;
import me.zhengjie.business.service.SbgsService;
import me.zhengjie.business.service.dto.OrderQueryCriteria;
import me.zhengjie.pay.domain.PaidQueryCriteria;
import me.zhengjie.pay.service.UnPaidService;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @author xiahongbo
* @date 2022-08-03
**/
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "订单管理管理")
@RequestMapping("/api/order")
public class OrderController {

    private final OrderService orderService;
    private final GsglService gsglService;
    private final SbgsService sbgsService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('order:list')")
    public void exportOrder(HttpServletResponse response, OrderQueryCriteria criteria) throws IOException {
        orderService.download(orderService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询订单管理")
    @ApiOperation("查询订单管理")
    public ResponseEntity<Object> queryOrder(OrderQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(orderService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增订单管理")
    @ApiOperation("新增订单管理")
    @PreAuthorize("@el.check('order:add')")
    public ResponseEntity<Object> createOrder(@Validated @RequestBody Order resources){
        return new ResponseEntity<>(orderService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改订单管理")
    @ApiOperation("修改订单管理")
    @PreAuthorize("@el.check('order:edit')")
    public ResponseEntity<Object> updateOrder(@Validated @RequestBody Order resources){
        orderService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除订单管理")
    @ApiOperation("删除订单管理")
    @PreAuthorize("@el.check('order:del')")
    public ResponseEntity<Object> deleteOrder(@RequestBody String[] ids) {
        orderService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping(value = "/groupByHlry2Count")
    @ApiOperation("根据月份，查询每月的订单数量")
    public ResponseEntity<Object> groupByHlry2Count(String month) {
        return new ResponseEntity<>(orderService.groupByHlry2Count(month), HttpStatus.OK);
    }

    @ApiOperation("结算查询（用于退费）")
    @GetMapping(value = "/orderCntList")
    public ResponseEntity<Object> orderCntList(OrderQueryCriteria criteria, Pageable pageable) {

        return new ResponseEntity<>(orderService.OrderCntList(criteria.getBisOrderHlrq(), pageable), HttpStatus.OK);
    }

    @ApiOperation("查询所有订单")
    @GetMapping(value = "/queryAllOrderList")
    public ResponseEntity<Object> queryAllOrderList(OrderQueryCriteria criteria, Pageable pageable) {
        Long userid = SecurityUtils.getCurrentUserId();
        UserDetails userDetails = SecurityUtils.getCurrentUser();
        log.info("userDetails:{}", userDetails);

        JSONObject userJson = new JSONObject(new JSONObject(userDetails).get("user"));
        JSONArray array = JSONUtil.parseArray(userJson.get("roles"));
        String roleString = array.toString();
        log.info("roleString:{}", roleString);
        if(roleString.indexOf("居家照护") != -1|| roleString.indexOf("居家机构双角色") != -1) {
            log.info("角色：居家照护、居家机构双角色");
            Gsgl gsgl = gsglService.queryGsgl(userid);
            criteria.setJgxx(gsgl.getBisGsglYljgdm());
        } else if(roleString.indexOf("商保公司") != -1) {
            log.info("角色：商保公司");
            Gsgl gsgl = gsglService.queryGsgl(userid);
            criteria.setSbgs(gsgl.getBisGsglId());
        }
        return new ResponseEntity<>(orderService.queryAllOrderList(criteria, pageable), HttpStatus.OK);
    }

    @Log("导出订单")
    @ApiOperation("导出订单")
    @GetMapping(value = "/queryAllOrderList/download")
    public void exportAllOrderList(HttpServletResponse response, OrderQueryCriteria criteria) throws IOException {
        Long userid = SecurityUtils.getCurrentUserId();
        UserDetails userDetails = SecurityUtils.getCurrentUser();
        log.info("userDetails:{}", userDetails);

        JSONObject userJson = new JSONObject(new JSONObject(userDetails).get("user"));
        JSONArray array = JSONUtil.parseArray(userJson.get("roles"));
        String roleString = array.toString();
        log.info("roleString:{}", roleString);
        if(roleString.indexOf("居家照护") != -1|| roleString.indexOf("居家机构双角色") != -1) {
            log.info("角色：居家照护、居家机构双角色");
            Gsgl gsgl = gsglService.queryGsgl(userid);
            criteria.setJgxx(gsgl.getBisGsglYljgdm());
        } else if(roleString.indexOf("商保公司") != -1) {
            log.info("角色：商保公司");
            Gsgl gsgl = gsglService.queryGsgl(userid);
            criteria.setSbgs(gsgl.getBisGsglId());
        }

        orderService.downloadAllOrderVo(orderService.queryAllOrderList(criteria), response);
    }
}